﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QLZJFurnitureSCM.Model;
using QLZJFurnitureSCM.BLL;
using System.Threading;

namespace QLZJFurnitureSCM.WinForm
{
    public partial class FrmContact : Form
    {
        private bool needUpdate = false;
        private bool hasUpdate = false;

        private ContactService contactService = null;
        //private OrderService oderService = null;
        private List<Contact> lstContact = null;
        private List<Order> lstOrder = null;
        private List<Order> lstOrderShow = null;

        public FrmContact()
        {
            InitializeComponent();
            contactService = new ContactService();
            lstContact = contactService.FindAllContacts();
            InitOrders();
            dataGridViewContact.DataSource = lstContact;
            SetDgvHeaderText();
        }

        private void SetDgvHeaderText()
        {

            DataGridViewCellStyle priceCellStyle = new DataGridViewCellStyle();
            priceCellStyle.Format = "C1";
            priceCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            /*
            DataGridViewTextBoxColumn colOrderId = new DataGridViewTextBoxColumn();
            colOrderId.Name = "OrderId";
            colOrderId.Visible = false;
            DataGridViewTextBoxColumn colOrderNo = new DataGridViewTextBoxColumn();
            colOrderNo.Name = "OrderNo";
            colOrderNo.HeaderText = "订单编号";
            DataGridViewTextBoxColumn colOrderContact = new DataGridViewTextBoxColumn();
            colOrderContact.Name = "OrderContact";
            colOrderContact.HeaderText = "客户";
            DataGridViewTextBoxColumn colOrderTime = new DataGridViewTextBoxColumn();
            colOrderTime.Name = "OrderTime";
            colOrderTime.HeaderText = "下单时间";
            DataGridViewTextBoxColumn colOrderDriveEmployee = new DataGridViewTextBoxColumn();
            colOrderDriveEmployee.Name = "OrderDriveEmployee";
            colOrderDriveEmployee.HeaderText = "司机";
            DataGridViewTextBoxColumn colOrderByUser = new DataGridViewTextBoxColumn();
            colOrderByUser.Name = "OrderByUser";
            colOrderByUser.HeaderText = "操作人";

            DataGridViewCheckBoxColumn colOrderPayStatus = new DataGridViewCheckBoxColumn();
            colOrderPayStatus.Name = "OrderPayStatus";
            colOrderPayStatus.HeaderText = "支付";

            DataGridViewTextBoxColumn colOrderPay = new DataGridViewTextBoxColumn();
            colOrderPay.Name = "OrderPay";
            colOrderPay.DefaultCellStyle = priceCellStyle;
            colOrderPay.HeaderText = "金额";

            dgvColArr = new DataGridViewColumn[]
                {
                    colOrderId,
                    colOrderNo,
                    colOrderContact,
                    colOrderTime,
                    colOrderDriveEmployee,
                    colOrderByUser,
                    colOrderPayStatus,
                    colOrderPay
                };*/
            

            //dataGridViewOrders.Columns.AddRange();
            dataGridViewContact.Columns["ContactId"].Visible = false;
            dataGridViewContact.Columns["ContactName"].HeaderText = "姓名";
            dataGridViewContact.Columns["ContactPhone"].HeaderText = "电话";
            dataGridViewContact.Columns["ContactDiscount"].HeaderText = "折扣";
            dataGridViewContact.Columns["ContactAddress"].HeaderText = "地址";

            //dataGridViewOrders.DataSource = lstOrder[0];
            /*
            dataGridViewOrders.Columns["OrderId"].Visible = false;
            dataGridViewOrders.Columns["OrderNo"].HeaderText = "订单号";
            dataGridViewOrders.Columns["OrderContact"].HeaderText = "客户";
            dataGridViewOrders.Columns["OrderTime"].HeaderText = "下单时间";
            dataGridViewOrders.Columns["OrderDriveEmployee"].HeaderText = "司机";
            dataGridViewOrders.Columns["OrderByUser"].HeaderText = "操作员";
            dataGridViewOrders.Columns["OrderPayStatus"].HeaderText = "支付";
            //dataGridViewOrders.Columns["OrderPayStatus"]. = dgvChkCell;
            dataGridViewOrders.Columns["OrderPay"].HeaderText = "金额";
            dataGridViewOrders.Columns["OrderPay"].DefaultCellStyle = priceCellStyle;

            dataGridViewOrders.Rows.Clear();*/
            /*
            decimal sum = (from t in lstPurchase select t.PurchaseTotalPrice).Sum();
            string sumChs = ConvertToChinese(sum);
            this.toolStripStatusLabelFrmRecordView.Text = string.Format("历史统计得:进货 {0} 次, 商品 {1} 件, 资金: {2} 元 合: {3}.", lstPurchase.Count, (from t in lstPurchase select t.PurchaseCount).Sum(), sum.ToString("C1"), sumChs);
             */

            //cellMouseEventArgs = new DataGridViewCellMouseEventArgs(1, 1, dataGridViewOrders.Location.X, dataGridViewOrders.Location.Y, new MouseEventArgs(MouseButtons.Left, 1, MousePosition.X, MousePosition.Y, 1));
        }

        private void FrmContact_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'furnitureDataSet.Contacts' table. You can move, or remove it, as needed.
            /*try
            {
               this.contactsTableAdapter.Fill(this.furnitureDataSet.Contacts);
            }
            catch (System.Data.SqlClient.SqlException)
            {
                MessageBox.Show("链接数据库发生异常, 请关闭重试.", "错误");
            }*/
            this.toolStripStatusLabelFrmContact.Text = string.Format("现有客户一共 {0} 位", lstContact.Count);

            //new Thread(new ThreadStart(InitOrders)).Start();
        }

        private void InitOrders()
        {
            lstOrder = new OrderService().FindAll();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            hasUpdate = true;
        }

        private object ObjSave = null;

        private void dataGridViewContact_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            ObjSave = dataGridViewContact[e.ColumnIndex, e.RowIndex].Value;
        }

        private void dataGridViewContact_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewCell currentCell = dataGridViewContact[e.ColumnIndex, e.RowIndex];
            string columnName = dataGridViewContact.Columns[e.ColumnIndex].Name;
            if ("contactDiscount".Equals(columnName))
            {
                if (!ValidateDiscountFormat(currentCell))
                {
                    MessageBox.Show("请输入一个有效的折扣数值, 如8折:8或8.0, 8.8折:8.8", "错误");
                    return;
                }
            }
            if (ObjSave.GetType() == typeof(DBNull))
            {
                if(null == currentCell.Value)
                    return;
            }
            if (!currentCell.Value.ToString().Equals(ObjSave.ToString()))
            {
                currentCell.Style.ForeColor = Color.Red;
                this.needUpdate = true;
                this.hasUpdate = false;
            }
        }

        private bool ValidateDiscountFormat(DataGridViewCell currentCell)
        {
            decimal result;
            if (!decimal.TryParse(currentCell.Value.ToString(), out result))
                return false;
            return true;
        }

        private void FrmContact_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.needUpdate)
            {
                if (!this.hasUpdate)
                {
                    DialogResult result = MessageBox.Show("数据已更改, 是否在离开前更新到数据库?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (DialogResult.Yes == result)
                        MessageBox.Show("Update");
                        //this.contactsTableAdapter.Update(this.furnitureDataSet.Contacts);
                }
            }
        }

        private void dataGridViewContact_Paint(object sender, PaintEventArgs e)
        {
            for (int i = 0; i < this.dataGridViewContact.Rows.Count; i += 2)
                this.dataGridViewContact.Rows[i].DefaultCellStyle.BackColor = SystemColors.ActiveBorder;
        }

        private void dataGridViewContact_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //MessageBox.Show(dataGridViewContact.Columns[e.ColumnIndex].Name);
            int index = dataGridViewContact.Columns["contactName"].Index;
            string contactName = dataGridViewContact[index, e.RowIndex].Value.ToString();
            lstOrderShow = (from o in lstOrder where o.OrderContact.Equals(contactName) select o).ToList();
            dataGridViewOrders.Rows.Clear();
            decimal total = 0M;
            foreach(Order order in lstOrderShow)
            {
                dataGridViewOrders.Rows.Add(new Object[] {
                    order.OrderNo,
                    order.OrderTime,
                    order.OrderDriveEmployee,
                    order.OrderByUser,
                    order.OrderPayStatus,
                    order.OrderPay
                });
                total += order.OrderPay;
            }
            toolStripStatusLabelOP.Text = string.Format("[{0}]客户消费次数: {1}次, 合计金额: {2}元.", contactName, lstOrderShow.Count, total);

            /*
            if (null != lstOrderShow)
            {
                dataGridViewOrders.DataSource = lstOrderShow;
            }
            else
                dataGridViewOrders.Rows.Clear();*/
        }

        private void btnContactDelete_Click(object sender, EventArgs e)
        {
            if (this.dataGridViewContact.SelectedRows.Count == 0)
                return;
            if (DialogResult.Yes == MessageBox.Show(this, "确认删除此客户?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
            {
                List<Contact> lstContactDel = new List<Contact>();
                Contact contact = null;
                //List<DataGridViewRow> lstDgvRow = new List<DataGridViewRow>();
                foreach (DataGridViewRow row in this.dataGridViewContact.SelectedRows)
                {
                    contact = new Contact();
                    contact.ContactId = int.Parse(row.Cells["ContactId"].Value.ToString());
                    lstContactDel.Add(contact);
                    //lstDgvRow.Add(row);
                }
                /*
                foreach(DataGridViewRow row in lstDgvRow)
                {
                    dataGridViewContact.Rows.Remove(row);
                }*/
                //foreach(Contact c in lstContactDel)
                if (contactService.DeleteBatch(lstContactDel))
                    lblStatus.Text = "删除成功.";
                else
                    lblStatus.Text = "删除失败.";
                lstContact = contactService.FindAllContacts();
                dataGridViewContact.DataSource = lstContact;
            }
        }

        private void btnContactNew_Click(object sender, EventArgs e)
        {
            this.panelOP.Visible = true;
            this.txtContactName.Text = "";
            this.txtContactPhone.Text = "";
            this.txtContactAddr.Text = "";
            this.txtContactDiscount.Text = "";
            this.txtContactName.ReadOnly = false;
            this.btnContactModify.Enabled = false;
            this.btnContactDelete.Enabled = false;
        }

        private void btnOperator_Click(object sender, EventArgs e)
        {
            //if failure, hide panel
            string contactName = this.txtContactName.Text;
            string contactPhone = this.txtContactPhone.Text;
            string contactAddr = this.txtContactAddr.Text;
            string contactDiscount = this.txtContactDiscount.Text;
            Contact contact = new Contact();
            contact.ContactName = contactName;
            contact.ContactPhone = contactPhone;
            contact.ContactAddress = contactAddr;
            contact.ContactDiscount = decimal.Parse(contactDiscount);
            if (this.btnContactModify.Enabled)
            {
                int contactId = int.Parse(this.lblContactId.Text);
                contact.ContactId = contactId;
                if(contactService.Update(contact))
                {
                    lblStatus.Text = "更新成功";
                    this.panelOP.Visible = false;
                }
                else
                    lblStatus.Text = "更新失败, 请修改重试.";
            }
            else
            {
                int count = (from c in lstContact where c.ContactName.Equals(contactName) select c).Count();
                if (count == 0)
                {
                    if (contactService.Insert(contact).ContactId > 0)
                    {
                        lblStatus.Text = "新增成功";
                        this.panelOP.Visible = false;
                    }
                    else
                        lblStatus.Text = "新增失败, 请修改重试.";
                }
                else
                    lblStatus.Text = "客户姓名不能重复添加, 请修改重试.";

            }
        }

        private void btnContactModify_Click(object sender, EventArgs e)
        {
            this.panelOP.Visible = true;
            if (this.dataGridViewContact.SelectedRows.Count > 0)
            {
                this.txtContactName.Text = this.dataGridViewContact.SelectedRows[0].Cells["ContactName"].Value.ToString();
                this.txtContactPhone.Text = this.dataGridViewContact.SelectedRows[0].Cells["ContactPhone"].Value.ToString();
                this.txtContactAddr.Text = this.dataGridViewContact.SelectedRows[0].Cells["ContactAddress"].Value.ToString();
                this.txtContactDiscount.Text = this.dataGridViewContact.SelectedRows[0].Cells["ContactDiscount"].Value.ToString();
                this.lblContactId.Text = this.dataGridViewContact.SelectedRows[0].Cells["ContactId"].Value.ToString();
                this.txtContactName.ReadOnly = true;
                this.btnContactNew.Enabled = false;
                this.btnContactDelete.Enabled = false;
            }
            else
                MessageBox.Show("请先选择要修改的客户.", "提示");
            
        }

        private void txtContactDiscount_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsNumber(e.KeyChar) && !Char.IsPunctuation(e.KeyChar) && !Char.IsControl(e.KeyChar))
                e.Handled = true;
            else if (Char.IsPunctuation(e.KeyChar))
            {
                if (e.KeyChar == '.')
                {
                    if (((TextBox)sender).Text.LastIndexOf('.') != -1)
                        e.Handled = true;
                }
                else
                    e.Handled = true;
            }
        }

        private void txtContactDiscount_Leave(object sender, EventArgs e)
        {
            decimal result;
            if(!decimal.TryParse(this.txtContactDiscount.Text, out result))
            {
                MessageBox.Show("请输入有效的折扣数值, 如原价85%, 请输入8.5.", "错误");
                this.txtContactDiscount.Focus();
                this.txtContactDiscount.SelectAll();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.panelOP.Visible = false;
            this.btnContactNew.Enabled = true;
            this.btnContactDelete.Enabled = true;
            this.btnContactModify.Enabled = true;
        }


    }
}
